//
//  UIListView.m
//  List
//
//  Created by Hunk on 12-2-11.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "UIListView.h"
#import "EGORefreshTableHeaderView.h"
#import "UIListViewCell.h"
#import "AsyncLoadingImageView.h"

#define SAFE_RELEASE(p) if(p){[p release]; p = nil;}

@implementation UIListView
@synthesize delegate          = _delegate;
@synthesize dataSource        = _dataSource;
//@synthesize listViewDataArray = _listViewDataArray;
@synthesize hasMore           = _hasMore;
@synthesize resetListView     = _resetListView;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) 
    {
        // Init variable
        _bIsReloading = NO;
        _listViewDataArray = [[NSMutableArray alloc] init];
        
        // Init UITableView
        _tableView = [[UITableView alloc] initWithFrame:self.bounds];
       // [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
        [_tableView setDataSource:self];
        [_tableView setDelegate:self];
        [self addSubview:_tableView];
        
        // Init EGORefreshTableHeaderView
        _refreshHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0, 0.0 - _tableView.bounds.size.height, self.bounds.size.width, self.bounds.size.height)];
        [_refreshHeaderView setDelegate:self];
        [_tableView addSubview:_refreshHeaderView];
        
        // FooterView
        UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 44.0)];
        [footerView setBackgroundColor:[UIColor redColor]];
        [_tableView setTableFooterView:footerView];
        _tableView.tableFooterView.hidden = YES;
        [footerView release];
    }
    return self;
}

- (void)setDelegate:(id<UIListViewDelegate>)delegate
{
    if(_delegate != delegate)
    {
        [_delegate release];
        
        _delegate = [delegate retain];
    }
}

- (void)setDataSource:(id<UIListViewDataSource>)dataSource
{
    if(_dataSource != dataSource)
    {
        [_dataSource release];
        
        _dataSource = [dataSource retain];
    }
}

- (void)appendDataArray:(NSArray *)dataArray
{
    if(_listViewDataArray && dataArray && [dataArray count] != 0)
    {
        [_listViewDataArray addObjectsFromArray:dataArray];
        
        // Reload tableView
        [_tableView reloadData];
    }
}

- (void)setHasMore:(BOOL)hasMore
{
    _hasMore = hasMore;
    
    _tableView.tableFooterView.hidden = !_hasMore;
}

- (void)setResetListView:(BOOL)resetListView
{
    _resetListView = resetListView;
    
    if(_resetListView)
    {
        if(_listViewDataArray != nil && [_listViewDataArray count] != 0)
        {
            [_listViewDataArray removeAllObjects];
            
            // Reload tableView
            [_tableView reloadData];
        }
    }
}

#pragma mark - 
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(_dataSource && [_dataSource respondsToSelector:@selector(numberOfRowsInListView:)])
    {
        return [_dataSource numberOfRowsInListView:self];
    }
    else if(nil != _listViewDataArray)
    {   
        return [_listViewDataArray count];
    }
    else
    {
        return 0;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

     static NSString *CellIdentifier = @"Cell";
     UIListViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
     if (cell == nil) 
     {
         cell = [[[UIListViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
                                       reuseIdentifier:CellIdentifier] autorelease];
     
         // 把这个view添加到数组，重置时需要移出
     }

    [cell setListViewCellData:indexPath.row];

/*
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) 
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault 
                                       reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // Configure the cell...
    cell.textLabel.text = [NSString stringWithFormat:@"%d", indexPath.row];
    */
    return cell;
}

#pragma mark -
#pragma mark UITableViewDelegate Method
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    if(_dataSource && [_dataSource respondsToSelector:@selector(heightForRowInListView:)])
    {
        return [_dataSource heightForRowInListView:self];
    }

    return 114.0;
}

#pragma mark -
#pragma mark UIScrollViewDelegate Methods
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{		
	[_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    
    // 滑动到最底部时进行加载
    if(((scrollView.contentOffset.y + scrollView.frame.size.height) > scrollView.contentSize.height)&& !_bIsReloading)
    { 
        if(_delegate && [_delegate respondsToSelector:@selector(fetchMoreData:)])
        {
            _bIsReloading = YES;
            
            [_delegate fetchMoreData:self];
        }
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{   
    [_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
//    UITableViewCell *cell = [_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1]];
    
    // 滑动停止
//    int nRow = _tableView.bounds.size.height / 40.0;
//    
//    int nIndex = scrollView.contentOffset.y / 40.0;
//    
//    for(int i = nIndex; i < nRow + nIndex; i ++)
//    {
//        
//    }
}
    
- (void)scrollListView
{
    [_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[_listViewDataArray count] - 1 inSection:0] 
                      atScrollPosition:UITableViewScrollPositionBottom 
                              animated:YES];
}

#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods
- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view
{	
    // 刷新开始动作
    if(_delegate && [_delegate respondsToSelector:@selector(refreshListView:)])
    {
        _bIsReloading = YES;
        
        [_delegate refreshListView:self];
    }
    else
    {
        [self performSelector:@selector(finishRefreshListView) withObject:nil afterDelay:1.0f];
    }
}

- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view
{	
	return _bIsReloading; // should return if data source model is reloading
}

- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view
{	
	return [NSDate date]; // should return date data source was last changed
}

// 刷新动作结束
- (void)finishRefreshListView
{	
	//  model should call this when its done loading
    _bIsReloading = NO;

    [_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:_tableView];
}

- (void)dealloc
{
    SAFE_RELEASE(_tableView)
    SAFE_RELEASE(_refreshHeaderView)
    SAFE_RELEASE(_delegate)
    SAFE_RELEASE(_dataSource)
    SAFE_RELEASE(_listViewDataArray)
    
    [super dealloc];
}

@end
